package com.m.IO;

import java.io.*;

/**
 * 对象序列化
 * ObjectOutputStream/ObjectInputStream 可将对象写入到文件中
 * 传输对象的过程叫做序列化（读）和反序列化（取）
 * 没有序列化的值都没有存入到文件
 * ObjectInputStream读到文件尾部最后返回java.io.EOFException
 * transient关键字
 * @author Mc.Chai
 * @program: Java基础
 * @create 2021-11-21-14:53 14:53
 */
public class TestObjectStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student student1=new Student("张三",13,"男",new Address());
        Student student2=new Student("李四",13,"男",new Address());
        Student student3=new Student("王五",14,"男",new Address());
        FileOutputStream fileOutputStream=new FileOutputStream("Object.txt");
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(student1);
        objectOutputStream.writeObject(student2);
        objectOutputStream.writeObject(student3);


        FileInputStream fileInputStream = new FileInputStream("Object.txt");
        ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
        /**
         * 循环的取出文件中的内容，读取到文件的尾部报出异常EOFException而执行catch中的break
         * 而终止循环
         * */
        while (true){
            try {
                Student stu=(Student) objectInputStream.readObject();
                System.out.println(stu.toString());
            } catch (EOFException e) {
                break;
            }
        }

    }
}
/**
 * 实现序列化的对象必须实现Serializable接口
 * 必须保证其所有的属性均可序列化
 * transient修饰为临时属性，不参与序列化
 * 包装类型都实现了Serializable接口
 * */
class Student implements Serializable {

    String name;
    Integer age;
    String sex;
    transient Address address;  //transient不参与序列化

    public Student(String name, Integer age, String sex, Address address) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", address=" + address +
                '}';
    }
}
class Address implements Serializable{

}
